package com.cy.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cy.common.entity.Result;
import com.cy.common.exception.CommonException;
import com.cy.common.utils.JwtUtils;
import com.cy.mapper.UserRoleMapper;
import com.cy.pojo.Academy;
import com.cy.pojo.Department;
import com.cy.pojo.User;
import com.cy.pojo.UserRole;
import com.cy.pojo.vo.*;
import com.cy.service.AcademyService;
import com.cy.service.AchievementService;
import com.cy.service.DepartmentService;
import com.cy.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static net.sf.jsqlparser.util.validation.metadata.NamedObject.user;

/**
 * @author 残影
 * @description 用户信息
 * @date 2022-04-13
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户信息模块")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private BCryptPasswordEncoder bcryptPasswordEncoder;

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private AcademyService academyService;

    /**
     * 根据ID查询用户信息
     */
    @GetMapping("{id}")
    @ApiOperation("根据ID查询用户信息")
    public Result findById(@PathVariable Integer id) {
        User user = userService.getById(id);
        if (user != null) {
            return Result.ok("查询用户信息成功", user);
        } else {
            return Result.failed(201, "没有该用户信息");
        }
    }

    /**
     * 分页查询用户信息
     */
    @ApiOperation("分页查询用户信息")
    @GetMapping("/list")
    public Result list(SearchUserVo searchVo) {
        //分页构造器
        Page<User> buildPage = new Page<>(searchVo.getPage(), searchVo.getLimit());
        //条件构造器
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(searchVo.getName())) {
            queryWrapper.like("username", searchVo.getName());
        }
        if (ObjectUtils.isNotEmpty(searchVo.getAcademyId())) {
            queryWrapper.eq("academy_id", searchVo.getAcademyId());
        }
        if ((ObjectUtils.isNotEmpty(searchVo.getDepartmentId()))) {
            queryWrapper.eq("department_id", searchVo.getDepartmentId());
        }
        IPage<User> pageList = userService.page(buildPage, queryWrapper);

        List<UserQueryVo> userQueryVoList = new ArrayList<>();
        List<User> userList = pageList.getRecords();
        List<Department> departmentList = departmentService.list();
        List<Academy> academyList = academyService.list();

        userList.forEach(user1 -> {
            UserQueryVo userQueryVo = new UserQueryVo();
            BeanUtils.copyProperties(user1, userQueryVo);
            departmentList.forEach(department -> {
                if (department.getDepartmentId() == user1.getDepartmentId()) {
                    userQueryVo.setDepartmentName(department.getDepartmentName());
                }
            });
            academyList.forEach(academy -> {
                if (academy.getAcademyId() == user1.getAcademyId()) {
                    userQueryVo.setAcademyName(academy.getAcademyName());
                }
            });
            userQueryVoList.add(userQueryVo);
        });
        return Result.ok("查询成功", userQueryVoList).put("total", pageList.getTotal());
    }

    /**
     * 保存用户信息
     */
    @PostMapping
    @ApiOperation("保存用户信息")
    public Result save(@RequestBody UserVo userVo, HttpServletRequest request) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", userVo.getUsername()).or(o ->
                o.eq("phone_number", userVo.getPhoneNumber())
        );
        List<User> list = userService.list(wrapper);
        if (list.size() > 0) {
            throw new CommonException("用户名或电话号码已经被使用");
        }
        Long currentUserId = JwtUtils.getUserIdByRequest(request);
        User currentUser = userService.getById(currentUserId);
        User user = new User();
        BeanUtils.copyProperties(userVo, user);
        user.setPassword(bcryptPasswordEncoder.encode(user.getPassword()));
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        user.setCreateBy(currentUser.getNickName());
        user.setUpdateBy(currentUser.getNickName());
        userService.save(user);
        return Result.ok("保存用户用户信息成功", user);
    }

    /**
     * 修改用户信息
     */
    @PutMapping("{id}")
    @ApiOperation("修改用户信息")
    public Result update(@RequestBody UserVo userVo, @PathVariable Long id, HttpServletRequest request) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", userVo.getUsername()).or(o ->
                o.eq("phone_number", userVo.getPhoneNumber())
        );
        List<User> list = userService.list(wrapper);
        if (list.size() > 1) {
            throw new CommonException("用户名或电话号码已经被使用");
        }

        Long currentUserId = JwtUtils.getUserIdByRequest(request);
        User currentUser = userService.getById(currentUserId);

        User user = userService.getById(id);
        if (ObjectUtils.isEmpty(user)) {
            throw new CommonException("用户不存在");
        }
        BeanUtils.copyProperties(userVo, user);
        user.setPassword(bcryptPasswordEncoder.encode(user.getPassword()));
        user.setUpdateTime(new Date());
        user.setUpdateBy(currentUser.getNickName());

        boolean b = userService.saveOrUpdate(user);
        if (b) {
            return Result.ok("修改用户信息成功", user);
        } else {
            return Result.failed("修改用户信息失败");
        }
    }

    /**
     * 删除用户信息
     */
    @DeleteMapping("{id}")
    @ApiOperation("删除用户信息")
    public Result delete(@PathVariable Long id) {
        boolean b = userService.removeById(id);
        if (b) {
            return Result.ok("删除用户信息成功");
        } else {
            return Result.failed("删除用户信息失败");
        }
    }
}
